package com.secxiot.provider.system.service.impl;

import com.secxiot.common.constant.ServerStatusEnum;
import com.secxiot.common.exception.BaseRuntimeException;
import com.secxiot.common.utils.CachedBeanCopier;
import com.secxiot.common.utils.IdWorker;
import com.secxiot.provider.system.dao.*;
import com.secxiot.provider.system.dto.AppBannerDto;
import com.secxiot.provider.system.dto.AppNewsDto;
import com.secxiot.provider.system.dto.AppVersionDto;
import com.secxiot.provider.system.dto.FileLogDto;
import com.secxiot.provider.system.entity.*;
import com.secxiot.provider.system.service.SystemService;
import com.secxiot.provider.system.vo.AppRegimeVo;
import com.secxiot.provider.system.vo.DataDictVo;
import com.secxiot.provider.system.vo.FileLogVo;
import com.secxiot.provider.system.vo.FilesStorageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Transactional
@Service
public class SystemServiceImpl implements SystemService {

    @Autowired
    private SystemMapper systemMapper;

    @Autowired
    FileLogMapper fileLogMapper;

    @Autowired
    private AppVersionDao appVersionDao;

    @Autowired
    private AppBannerDao appBannerDao;

    @Autowired
    private AppNewsDao appNewsDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private AppRecommendDao appRecommendDao;

    @Autowired
    private FilesStorageMapper filesStorageMapper;

    @Autowired
    private AppRegimeMapper appRegimeMapper;

    @Override
    public List<DataDictVo> listDataDict(String parentCode) {
        return systemMapper.selectDatadict(parentCode);
    }

    @Override
    public Long saveFileLog(FileLog fileLog) {
        Long id = idWorker.nextId();
        if (fileLog.getId() == null) {
            fileLog.setId(id);
        }
        fileLog.setUsedFlag(0);
        Date date = new Date();
        fileLog.setCreateDate(date);
        fileLogMapper.insertSelective(fileLog);
        return fileLog.getId();
    }

    @Override
    public FileLogDto getFileUri(Long logId) {
        FileLog fileLog = fileLogMapper.selectByPrimaryKey(logId);
        FileLogDto fileLogDto = new FileLogDto();
        if (fileLog != null) {
            BeanUtils.copyProperties(fileLog, fileLogDto);
            fileLogDto.setFileLogId(fileLog.getId());
            return fileLogDto;
        }
        return null;
    }

    @Override
    public Long useFileLogs(List<Long> logIds) {
        FileLog fileLog = new FileLog();
        fileLog.setUsedFlag(1);
        FileLogExample example = new FileLogExample();
        example.createCriteria().andIdIn(logIds);
        int i = fileLogMapper.updateByExampleSelective(fileLog, example);
        return Long.valueOf(i);
    }

    @Override
    public List<FileLogVo> selectFileByCode(String code) {
        List<FileLog> fileLogs = fileLogMapper.selectFileByCode(code);
        List<FileLogVo> fileLogVos= fileLogs.stream().map(p -> {
            FileLogVo fileLogVo = new FileLogVo();
            fileLogVo.setFileLogId(p.getId());
            CachedBeanCopier.copy(p, fileLogVo);
            return fileLogVo;
        }).collect(Collectors.toList());
        return fileLogVos;
    }

    @Override
    public AppVersionDto getAppVersion(String platform, String clientType) {
        AppVersionExample example = new AppVersionExample();
        example.setPageNo(1);
        example.setPageSize(1);
        example.setOrderByClause("version DESC");
        example.createCriteria().andClientTypeEqualTo(clientType).andPlatformEqualTo(platform).andValidEqualTo(1);
        List<AppVersion> versions = appVersionDao.selectByExample(example);
        if (!CollectionUtils.isEmpty(versions)) {
            AppVersionDto vdt = new AppVersionDto();
            CachedBeanCopier.copy(versions.get(0), vdt);
            return vdt;
        } else {
            throw new BaseRuntimeException(ServerStatusEnum.NOT_FOUND);
        }
    }

    @Override
    public List<AppBannerDto> getAppBanner(Long userId, Long hospitalId) {
        AppBannerExample example = new AppBannerExample();
        example.setOrderByClause("create_time DESC");
        AppBannerExample.Criteria criteria = example.createCriteria().andValidEqualTo(1);
        if (hospitalId != null) {
            criteria.andHospitalIdEqualTo(hospitalId);

        }
        List<AppBanner> list = null;
        int count = appBannerDao.countByExample(example);
        if (count > 0) {
            list = appBannerDao.selectByExample(example);
        } else {
            example.clear();
            example.setOrderByClause("create_time DESC");
            example.createCriteria().andValidEqualTo(1);
            list = appBannerDao.selectByExample(example);
        }
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        } else {
            List<AppBannerDto> collect = list.stream().map(b -> {
                AppBannerDto d = new AppBannerDto();
                CachedBeanCopier.copy(b, d);
                return d;
            }).collect(Collectors.toList());
            return collect;
        }
    }

    @Override
    public List<AppNewsDto> getAppNews(Long userId, Long hospitalId) {
        AppNewsExample example = new AppNewsExample();
        example.setOrderByClause("create_time DESC");
        AppNewsExample.Criteria criteria = example.createCriteria().andValidEqualTo(1);
        if (hospitalId != null) {
            criteria.andHospitalIdEqualTo(hospitalId);

        }
        List<AppNews> list = null;
        int count = appNewsDao.countByExample(example);
        if (count > 0) {
            list = appNewsDao.selectByExample(example);
        } else {
            example.clear();
            example.setOrderByClause("create_time DESC");
            example.createCriteria().andValidEqualTo(1);
            list = appNewsDao.selectByExample(example);
        }
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        } else {
            List<AppNewsDto> collect = list.stream().map(b -> {
                AppNewsDto d = new AppNewsDto();
                CachedBeanCopier.copy(b, d);
                return d;
            }).collect(Collectors.toList());
            return collect;
        }
    }

    @Override
    public List<AppRecommend> getAppRecommends(Long userId, Long hospitalId, Long pageNo, Long pageSize) {
        List<AppRecommend> list = appRecommendDao.getAppRecommendList(userId,hospitalId, pageNo, pageSize);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list;
    }

    @Override
    public AppRecommend getAppRecommendById(Long recommendId) {
        return appRecommendDao.selectByPrimaryKey(recommendId);
    }

    @Override
    public List<FilesStorageVo> selectFilesStorage(Long userId,Long hospitalId,Integer pageNo, Integer pageSize, Integer isPage, String searchName) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("hospitalId", hospitalId);
        if (isPage == 1) {
            map.put("pageNo", pageNo * pageSize);
            map.put("pageSize", pageSize);
        }
        map.put("isPage", isPage);
        map.put("searchName", searchName);

        List<FilesStorageDo> filesStorageDos = filesStorageMapper.selectFilesStorageDo(map);

        List<FilesStorageVo> filesStorageVos = filesStorageDos.stream().map(p -> {
            FilesStorageVo filesStorageVo = new FilesStorageVo();
            CachedBeanCopier.copy(p, filesStorageVo);
            return filesStorageVo;
        }).collect(Collectors.toList());

        return filesStorageVos;
    }

    @Override
    public FilesStorageVo getFilesStorageById(Long id) {

        FilesStorageVo filesStorageVo = new FilesStorageVo();
        FilesStorageDo filesStorageDo = filesStorageMapper.getFilesStorageById(id);
        CachedBeanCopier.copy(filesStorageDo, filesStorageVo);

        if (filesStorageVo != null) {
            if (filesStorageVo.getFilesCode() != null) {
                List<FileLogVo> fileLogList = selectFileByCode(filesStorageVo.getFilesCode());
                if (fileLogList != null) {
                    filesStorageVo.setFileList(fileLogList);
                }
            }
        }
        return filesStorageVo;
    }

    @Override
    public Long insertFilesStorage(FilesStorageVo filesStorageVo) {
        if ("".equals(filesStorageVo.getTitle())) {
            throw new BaseRuntimeException(ServerStatusEnum.FILESSTORAGE_TITLE_EMPTY);
        } else if (filesStorageVo.getPublishUserId() == null) {
            throw new BaseRuntimeException(ServerStatusEnum.FILESSTORAGE_PUBLISHUSER_EMPTY);
        } else {
            FilesStorageDo filesStorageDo = new FilesStorageDo();
            CachedBeanCopier.copy(filesStorageVo, filesStorageDo);
            filesStorageDo.setCreateTime(new Date());
            filesStorageDo.setValid(1);
            return filesStorageMapper.insert(filesStorageDo);
        }
    }

    @Override
    public Long updateFilesStorage(FilesStorageVo filesStorageVo) {
        if (filesStorageVo.getId() == null) {
            throw new BaseRuntimeException(ServerStatusEnum.ID_KEY_EMPTY);
        } else if ("".equals(filesStorageVo.getTitle())) {
            throw new BaseRuntimeException(ServerStatusEnum.FILESSTORAGE_TITLE_EMPTY);
        } else if (filesStorageVo.getPublishUserId() == null) {
            throw new BaseRuntimeException(ServerStatusEnum.FILESSTORAGE_PUBLISHUSER_EMPTY);
        } else {
            FilesStorageDo filesStorageDo = new FilesStorageDo();
            CachedBeanCopier.copy(filesStorageVo, filesStorageDo);
            filesStorageDo.setCreateTime(new Date());
            filesStorageDo.setValid(1);
            return filesStorageMapper.updateByPrimaryKey(filesStorageDo);
        }
    }

    @Override
    public List<AppRegimeVo> selectAppRegime(String type, Long hospitalId, Integer pageNo, Integer pageSize, Integer isPage, String searchName) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("hospitalId", hospitalId);
        map.put("type", type);
        if (isPage == 1) {
            map.put("pageNo", pageNo * pageSize);
            map.put("pageSize", pageSize);
        }
        map.put("isPage", isPage);
        map.put("searchName", searchName);
        return appRegimeMapper.selectAppRegimeDo(map);
    }

    @Override
    public AppRegimeVo getAppRegimeById(Long id) {
        AppRegimeVo appRegimeVo = new AppRegimeVo();
        AppRegimeDo appRegimeDo = appRegimeMapper.getAppRegimeById(id);
        if (appRegimeDo == null) {
            throw new BaseRuntimeException(ServerStatusEnum.LIST_EMPTY);
        }
        CachedBeanCopier.copy(appRegimeDo, appRegimeVo);
        return appRegimeVo;
    }

    /**
     * 删除文件
     * @param fileId
     * @return
     */
    @Override
    public int deleteFile(Long fileId) {
        return fileLogMapper.deleteByPrimaryKey(fileId);
    }

}
